package com.linzuo.generatorsql.demos.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author yx
 * 翻译工具类
 */
public class TranslatorUtils {

    /**
     * 对接的api为百度翻译
     */
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private static String appid = "20230428001659164";

    private static String securityKey = "_D70LZwdTU8LvsMOqaFW";

    /**
     * 发送查询
     * @param query
     * @return
     */
    public static String getTranslateResult(String query) {
        String from = "zh";
        String to = "en";
        try {
            Thread.sleep(1001);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, Object> params = new HashMap();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", appid);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = appid + query + salt + securityKey;
        params.put("sign", SecureUtil.md5(src));
        String rs = HttpUtil.get(TRANS_API_HOST, params);
        JSONObject jo = JSONUtil.parseObj(rs);
        String enStr = jo.getJSONArray("trans_result").getJSONObject(0).getStr("dst");
        if(enStr.length()>10&&enStr.indexOf(" ")>-1){
            enStr = enStr.split(" ")[0];
        }
        return enStr.toUpperCase(Locale.ROOT);
    }
}
